#!/bin/sh

. /usr/share/common

#COMMAND="/bin/env -- LD_PRELOAD=/lib/libimp_control.so $DAEMON_FULL"

check_ssl_certificates() {
	# Check if TLS is enabled in RTSP configuration
	if [ -f "/etc/streamer.d/rtsp.json" ] && command -v jct >/dev/null 2>&1; then
		TLS_ENABLED=$(jct /etc/streamer.d/rtsp.json get tls_enabled 2>/dev/null || echo "false")
		if [ "$TLS_ENABLED" = "true" ]; then
			CERT_FILE="/etc/ssl/certs/rtsp-server.crt"
			KEY_FILE="/etc/ssl/private/rtsp-server.key"

			# Check if certificates exist and are valid
			if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
				echo_info "TLS enabled but SSL certificates missing, generating..."
				if command -v generate-ssl-certs.sh >/dev/null 2>&1; then
					generate-ssl-certs.sh --quiet || echo_warning "Failed to generate SSL certificates"
				else
					echo_warning "SSL certificate generator not found"
				fi
			else
				# Check if certificate is expired or will expire soon (within 30 days)
				if command -v openssl >/dev/null 2>&1; then
					if ! openssl x509 -in "$CERT_FILE" -checkend 2592000 -noout >/dev/null 2>&1; then
						echo_warning "SSL certificate expires within 30 days, consider regenerating"
					fi
				fi
			fi
		fi
	fi
}

start() {
	echo_title "Starting Streamer"

	if is_streamer_disabled; then
		echo_error "Streamer disabled"
		exit 1
	fi

	# Check and generate SSL certificates if needed
	check_ssl_certificates

	start_daemon
}

stop() {
	echo_title "Stopping Streamer"

	if is_streamer_disabled; then
		echo_error "Streamer disabled"
		exit 1
	fi

	[ -f "$SNAPSHOT_FILE" ] && rm -f "$SNAPSHOT_FILE"

	stop_daemon
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop || true
		sleep 1
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
